import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { login as loginFn } from "@/api/user";
import type { LoginOption, tznUser } from "@/api/user/model";
import { removeToken, setToken } from "@/utils/auth";
import router from "@/router";
import { useLayoutStore } from "./layout";
import type { RouteRecordRaw } from "vue-router";

export const useUserStore = defineStore("user", () => {
  // 用户token
  const token = ref("");

  // 按钮级别权限
  const authoritys = ref([]);

  // 用户信息
  const tznUser = reactive<tznUser>({
    areaId: "",
    createTime: "",
    id: "",
    name: "",
    number: "",
    password: "",
    status: "",
    type: "",
  });

  // 左侧导航栏
  const menuList = ref<RouteRecordRaw[]>([]);


  const login = async (data: LoginOption) => {
    const res = await loginFn(data);
    // const router = useRouter();
    if (res.tznUser.type=='0') {
      router.push("/user")
    }else if (res.tznUser.type=='1') {
      router.push("/user")
    }else if (res.tznUser.type=='2') {
      router.push("/unDelivery")
    }else if (res.tznUser.type=='3') {
      router.push("/unDelivery")
    }
    
    setToken(res.token);
    token.value = res.token;
    Object.assign(tznUser, res.tznUser);
  };

  const exit = () => {
    token.value = "";
    removeToken();
    router.push("/login").then(() => {
      tznUser.areaId = null;
      tznUser.createTime = "";
      tznUser.id = "";
      tznUser.name = "";
      tznUser.number = "";
      tznUser.status = "";
      tznUser.password = "";
      tznUser.type = "";
      menuList.value = [];
      useLayoutStore().clear();
    });
  };

  return {
    login,
    token,
    tznUser,
    exit,
    menuList,
    authoritys
  };
}, {
  persist: true
});
